import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
from automation import NGReportAutomation
from config_manager import ConfigManager
import logging


class NGReportGUI:
    def __init__(self, master):
        self.master = master
        master.title("NG Report PPT 自动生成工具")
        
        # 配置
        self.config = {
            'excel_path': '',
            'output_excel_path': 'output/deviation_request_list.xlsx',
            'excel_sheet_name': 'Sheet1',
            'excel_color': 'red',  # 默认颜色
            'excel_keywords': ['NG', '偏差', '不合格'],
            'pdf_path': '',
            'output_image_dir': 'output/images',
            'pdf_keyword': 'NG',
            'ppt_output_path': 'output/ng_report.pptx'
        }
        
        # 创建界面
        self.create_widgets()
        
    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.master, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # Excel文件选择
        excel_frame = ttk.LabelFrame(main_frame, text="Excel文件设置", padding="10")
        excel_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Label(excel_frame, text="Excel文件:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.excel_path_var = tk.StringVar()
        ttk.Entry(excel_frame, textvariable=self.excel_path_var, width=50).grid(row=0, column=1, padx=5, pady=5)
        ttk.Button(excel_frame, text="浏览", command=self.select_excel_file).grid(row=0, column=2, padx=5, pady=5)
        
        ttk.Label(excel_frame, text="颜色:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.color_var = tk.StringVar(value=self.config['excel_color'])
        ttk.Entry(excel_frame, textvariable=self.color_var, width=20).grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
        
        ttk.Label(excel_frame, text="关键词:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.keywords_var = tk.StringVar(value=", ".join(self.config['excel_keywords']))
        ttk.Entry(excel_frame, textvariable=self.keywords_var, width=50).grid(row=2, column=1, padx=5, pady=5)
        
        # PDF文件选择
        pdf_frame = ttk.LabelFrame(main_frame, text="PDF文件设置", padding="10")
        pdf_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Label(pdf_frame, text="PDF文件:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.pdf_path_var = tk.StringVar()
        ttk.Entry(pdf_frame, textvariable=self.pdf_path_var, width=50).grid(row=0, column=1, padx=5, pady=5)
        ttk.Button(pdf_frame, text="浏览", command=self.select_pdf_file).grid(row=0, column=2, padx=5, pady=5)
        
        ttk.Label(pdf_frame, text="关键词:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.pdf_keyword_var = tk.StringVar(value=self.config['pdf_keyword'])
        ttk.Entry(pdf_frame, textvariable=self.pdf_keyword_var, width=50).grid(row=1, column=1, padx=5, pady=5)
        
        # 输出设置
        output_frame = ttk.LabelFrame(main_frame, text="输出设置", padding="10")
        output_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Label(output_frame, text="输出Excel路径:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.output_excel_var = tk.StringVar(value=self.config['output_excel_path'])
        ttk.Entry(output_frame, textvariable=self.output_excel_var, width=50).grid(row=0, column=1, padx=5, pady=5)
        
        ttk.Label(output_frame, text="输出图片目录:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.output_image_dir_var = tk.StringVar(value=self.config['output_image_dir'])
        ttk.Entry(output_frame, textvariable=self.output_image_dir_var, width=50).grid(row=1, column=1, padx=5, pady=5)
        
        ttk.Label(output_frame, text="输出PPT路径:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.ppt_output_var = tk.StringVar(value=self.config['ppt_output_path'])
        ttk.Entry(output_frame, textvariable=self.ppt_output_var, width=50).grid(row=2, column=1, padx=5, pady=5)
        
        # 操作按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, pady=10)
        
        ttk.Button(button_frame, text="运行", command=self.run_automation).grid(row=0, column=0, padx=5)
        ttk.Button(button_frame, text="重置", command=self.reset_fields).grid(row=0, column=1, padx=5)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = ttk.Label(main_frame, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.grid(row=4, column=0, sticky=(tk.W, tk.E))
        
        # 设置权重，使窗口可调整大小
        for i in range(4):
            main_frame.rowconfigure(i, weight=1)
        main_frame.columnconfigure(0, weight=1)
        
    def select_excel_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx *.xls")])
        if file_path:
            self.excel_path_var.set(file_path)
            self.config['excel_path'] = file_path
    
    def select_pdf_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("PDF文件", "*.pdf")])
        if file_path:
            self.pdf_path_var.set(file_path)
            self.config['pdf_path'] = file_path
    
    def reset_fields(self):
        self.excel_path_var.set("")
        self.color_var.set("red")
        self.keywords_var.set(", ".join(self.config['excel_keywords']))
        self.pdf_path_var.set("")
        self.pdf_keyword_var.set("NG")
        self.output_excel_var.set("output/deviation_request_list.xlsx")
        self.output_image_dir_var.set("output/images")
        self.ppt_output_var.set("output/ng_report.pptx")
        self.status_var.set("就绪")
    
    def run_automation(self):
        # 更新配置
        self.config['excel_path'] = self.excel_path_var.get()
        self.config['excel_color'] = self.color_var.get()
        self.config['excel_keywords'] = [kw.strip() for kw in self.keywords_var.get().split(",") if kw.strip()]
        self.config['pdf_path'] = self.pdf_path_var.get()
        self.config['pdf_keyword'] = self.pdf_keyword_var.get()
        self.config['output_excel_path'] = self.output_excel_var.get()
        self.config['output_image_dir'] = self.output_image_dir_var.get()
        self.config['ppt_output_path'] = self.ppt_output_var.get()

        # 获取日志记录器
        self.logger = logging.getLogger(__name__)

        # 更新全局配置管理器
        config_manager = ConfigManager()
        config_manager.update_config(self.config)
        
        # 验证输入
        if not self.config['excel_path']:
            messagebox.showerror("错误", "请选择Excel文件")
            return
        if not self.config['pdf_path']:
            messagebox.showerror("错误", "请选择PDF文件")
            return
        
        # 运行自动化流程
        self.status_var.set("运行中...")
        self.master.update()
        
        try:
            automation = NGReportAutomation(self.config)
            success = automation.run()
            
            if success:
                self.status_var.set("完成！")
                messagebox.showinfo("成功", "NG Report PPT生成完成！")
            else:
                self.status_var.set("运行失败")
                messagebox.showerror("错误", "生成NG Report PPT失败")
        except Exception as e:
            self.status_var.set("运行异常")
            messagebox.showerror("错误", f"运行时发生错误: {str(e)}")